package pers.weiney.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.weiney.mapper.ArticleMapper;
import pers.weiney.pojo.Article;
import pers.weiney.pojo.PageBean;
import pers.weiney.service.ArticleService;
import pers.weiney.utils.ThreadLocalUtil;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: @Weiney
 * @ClassName: ArticleServiceImpl
 * @Description: 文章服务层接口实现类
 * @Create: 2024-08-13
 **/
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void addArticle(Article article) {
        article.setCreateUser(ThreadLocalUtil.getId());
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.insert(article);
    }

    @Override
    public PageBean<Article> getAll(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 1. 创建PageBean对象
        PageBean<Article> pageBean = new PageBean<>();
        // 2. 开启分页查询【pageHelper】
        PageHelper.startPage(pageNum, pageSize);
        // 3. 调用Mapper
        Integer createUser = ThreadLocalUtil.getId();
        List<Article> articles = articleMapper.selectAllByPage(createUser, categoryId, state);
        // Page中提供了方法，可以获取PageHelper分页查询后的得到的总记录条数和当前页数据
        Page<Article> page = (Page<Article>) articles;
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    @Override
    public Article detail(Integer id) {
        return articleMapper.selectById(id);
    }

    @Override
    public void update(Article article) {
        // 设置更新时间
        article.setUpdateTime(LocalDateTime.now());
        // 调用mapper
        articleMapper.updateArticle(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.deleteById(id);
    }
}